<%@ page import="pojo.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="common.jsp" %>
<html>
<head>
    <title>首页</title>
    <style>
        .product-card {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            text-align: center; /* 居中显示商品卡片内容 */
        }

        .card {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            height: 100%;
        }

        .product-img {
            max-width: 100%;
            height: auto;
            margin: 0 auto; /* 使图片居中 */
        }

        .card-body {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
        }

        .card-title, .card-text {
            text-align: center;
        }
    </style>
    <script>
        $(document).ready(function () {
            loadProducts(); // 加载商品列表
            loadUserCart(); // 加载用户购物车信息
        });

        function loadProducts() {
            $.ajax({
                type: 'GET',
                url: '${pageContext.request.contextPath}/product?operation=getAllProducts',
                dataType: 'json',
                success: function (response) {
                    $('#productList').empty();

                    $.each(response.data, function (index, product) {
                        var productHtml =
                            '<div class="col-md-4 mb-4 product-card">' +
                            '<div class="card h-100">' + // 使用 h-100 类，保证商品卡片高度一致
                            '<img style="width: 150px;height: 150px" src="' + product.img + '" class="card-img-top product-img" alt="商品图片">' +
                            '<div class="card-body">' +
                            '<h5 class="card-title">' + product.name + '</h5>' +
                            '<p class="card-text">' + product.description + '</p>' +
                            '<button class="btn btn-primary" onclick="addToCart(' + product.id + ', \'' + product.img + '\')">加入购物车</button>' +
                            '</div>' +
                            '</div>' +
                            '</div>';

                        $('#productList').append(productHtml);
                    });
                },
                error: function (xhr, status, error) {
                    console.error('加载商品列表出错:', error);
                }
            });
        }

        function addToCart(productId, img) {
            var userJson = '<%= session.getAttribute("userJson") %>';
            var user = JSON.parse(userJson);

            if (!user || !user.id) {
                alert('请先登录');
                return;
            }

            $.ajax({
                type: 'POST',
                url: '${pageContext.request.contextPath}/cart?operation=addCartItem',
                data: {
                    userId: user.id,
                    productId: productId,
                    quantity: 1,
                    img: img // 商品图片URL
                },
                dataType: 'text',
                success: function (response) {
                    console.log('加入购物车成功:', response);
                    loadUserCart(); // 加载用户购物车信息
                },
                error: function (xhr, status, error) {
                    console.error('加入购物车失败:', error);
                }
            });
        }

        function loadUserCart() {
            var userJson = '<%= session.getAttribute("userJson") %>';
            var user = JSON.parse(userJson);

            if (user.id) {
                $.ajax({
                    type: 'GET',
                    url: '${pageContext.request.contextPath}/cart?operation=getCartItemsByUserId',
                    data: {
                        userId: user.id
                    },
                    dataType: 'json',
                    success: function (response) {
                        $('#userCart').empty();

                        var cartTableHtml =
                            '<table class="table table-bordered table-hover">' +
                            '<thead>' +
                            '<tr>' +
                            '<th scope="col">商品ID</th>' +
                            '<th scope="col">数量</th>' +
                            '<th scope="col">商品图片</th>' +
                            '</tr>' +
                            '</thead>' +
                            '<tbody>';

                        $.each(response.data, function (index, item) {
                            cartTableHtml +=
                                '<tr>' +
                                '<td>' + item.productId + '</td>' +
                                '<td>' + item.quantity + '</td>' +
                                '<td><img src="' + item.img + '" class="product-img" style="width: 100px;height: 100px"></td>' +
                                '</tr>';
                        });

                        cartTableHtml += '</tbody></table>';

                        $('#userCart').html(cartTableHtml);
                    },
                    error: function (xhr, status, error) {
                        console.error('加载购物车信息出错:', error);
                    }
                });
            }
        }
    </script>
</head>
<body>

<!-- 商品列表容器 -->
<div class="container">
    <div class="row" id="productList"></div>
</div>

<!-- 用户购物车信息容器 -->
<div class="container mt-4">
    <h4>用户购物车</h4>
    <div id="userCart"></div>
</div>

</body>
</html>
